package com.jkgh.remedium.states;

import com.jkgh.asin.State;
import com.jkgh.remedium.RemediumConstants;
import com.jkgh.remedium.RemediumServerClientConnection;

public class AuthenticateState extends State {
	
	private static final byte[] POLICY_CONTENTS = ("<?xml version=\"1.0\"?><cross-domain-policy><allow-access-from domain=\"*\" to-ports=\""+RemediumConstants.PORT+"\" /></cross-domain-policy>\0").getBytes();
	
	private final RemediumServerClientConnection connection;

	public AuthenticateState(RemediumServerClientConnection connection) {
		super(connection.getMachine());
		this.connection = connection;
	}

	@Override
	public void onBytesAvailable() {
		switch (machine.produceByte()) {
		
			case RemediumConstants.POLICY_ENFORCER:
				machine.consumeBytes(POLICY_CONTENTS, 0, POLICY_CONTENTS.length);
				machine.disconnectAfterAllWrites();
				break;
				
			case RemediumConstants.REGULAR_CLIENT:
				connection.onAuthenticated();
				break;
				
			default:
				machine.disconnect();
				break;
		}
	}

}
